/*
 *    Copyright (c) 2018-2025, nart All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: nart
 */

package com.nai365.nart.ware.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nai365.nart.common.core.exception.NoStockException;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.core.vo.WareSkuVo;
import com.nai365.nart.common.log.annotation.SysLog;
import com.nai365.nart.common.security.annotation.Inner;
import com.nai365.nart.ware.entity.WareSku;
import com.nai365.nart.ware.service.WareSkuService;
import com.nai365.nart.common.core.to.SkuHasStockTO;
import com.nai365.nart.ware.to.WareSkuLockTO;
import com.nai365.nart.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.nai365.nart.common.core.exception.BizCodeEnum.NO_STOCK_EXCEPTION;

/**
 * 商品库存
 *
 * @author baogs
 * @date 2022-07-02 13:21:19
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/waresku" )
@Api(value = "waresku", tags = "商品库存管理")
public class WareSkuController {

    private final  WareSkuService wareSkuService;


	/**
	 * 列表
	 */
	@GetMapping("/list")
	//@RequiresPermissions("ware:waresku:list")
	public R list(Page page , WareSku wareSku){

		return R.ok(wareSkuService.queryPage(page, wareSku));
	}

    /**
     * 分页查询
     * @param page 分页对象
     * @param wareSku 商品库存
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    public R getWareSkuPage(Page page, WareSku wareSku) {
        return R.ok(wareSkuService.page(page, Wrappers.query(wareSku)));
    }


    /**
     * 通过id查询商品库存
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(wareSkuService.getById(id));
    }

    /**
     * 新增商品库存
     * @param wareSku 商品库存
     * @return R
     */
    @ApiOperation(value = "新增商品库存", notes = "新增商品库存")
    @SysLog("新增商品库存" )
    @PostMapping
    public R save(@RequestBody WareSku wareSku) {
        return R.ok(wareSkuService.save(wareSku));
    }

    /**
     * 修改商品库存
     * @param wareSku 商品库存
     * @return R
     */
    @ApiOperation(value = "修改商品库存", notes = "修改商品库存")
    @SysLog("修改商品库存" )
    @PutMapping
    public R updateById(@RequestBody WareSku wareSku) {
        return R.ok(wareSkuService.updateById(wareSku));
    }

    /**
     * 通过id删除商品库存
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除商品库存", notes = "通过id删除商品库存")
    @SysLog("通过id删除商品库存" )
    @DeleteMapping("/{id}" )
    public R removeById(@PathVariable Long id) {
        return R.ok(wareSkuService.removeById(id));
    }


    /**
     * 导出excel 表格
     * @param wareSku 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    public List<WareSku> export(WareSku wareSku) {
        return wareSkuService.list(Wrappers.query(wareSku));
    }


	/**
	 * 锁定库存
	 * 库存解锁的场景
	 * 1）、下订单成功，订单过期没有支付被系统自动取消或者被用户手动取消，都要解锁库存
	 * 2）、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
	 * 3）、
	 */
	@PostMapping(value = "/lock/order")
	@Inner
	public R orderLockStock(@RequestBody WareSkuLockTO lockTO) {
		try {
			wareSkuService.orderLockStock(lockTO);
			return R.ok();
		} catch (NoStockException e) {
			return R.failed(NO_STOCK_EXCEPTION.getCode(), NO_STOCK_EXCEPTION.getMessage());
		}
	}

	/**
	 * 批量查询sku是否有库存
	 */
	@PostMapping("/hasstock")
	public R getSkusHasStock(@RequestBody List<Long> skuIds) {
		// skuId, stock
		List<SkuHasStockTO> result = wareSkuService.getSkusHasStock(skuIds);

		return R.ok().setData(result);
	}
	/**
	 * 批量查询sku是否有库存
	 */
	@PostMapping("/hasstock_inner")
	@Inner
	public R getSkusHasStockInner(@RequestBody List<Long> skuIds) {
		// skuId, stock
		List<SkuHasStockTO> result = wareSkuService.getSkusHasStock(skuIds);

		return R.ok().setData(result);
	}
	/**
	 * 新增商品库存
	 * @param wareSkus 商品库存
	 * @return R
	 */
	@ApiOperation(value = "新增商品库存", notes = "新增商品库存")
	@SysLog("新增商品库存" )
	@PostMapping("/save_inner")
	@Inner
	public R save_batch(@RequestBody List<WareSkuVo> wareSkus) {
		if (wareSkus.size() == 1) {
			WareSkuVo wareSkuVo = wareSkus.get(0);
			List<WareSku> list = wareSkuService.list(new LambdaQueryWrapper<WareSku>()
					.eq(WareSku::getSkuId, wareSkuVo.getSkuId())
					.eq(WareSku::getStock, wareSkuVo.getStock())
					.eq(WareSku::getStockLocked, 0)
					.eq(WareSku::getOwnerId, wareSkuVo.getOwnerId()));
			if (list.size() > 0){
				return R.failed("已上架库存");
			}
		}
		List<WareSku> collect = wareSkus.stream().map(item -> {
			WareSku wareSku = new WareSku();
			BeanUtil.copyProperties(item, wareSku);
			return wareSku;
		}).collect(Collectors.toList());
		return R.ok(wareSkuService.saveBatch(collect));
	}


	/**
	 * 删除
	 */
	@PostMapping("/delete")
	public R delete(@RequestBody Long[] ids) {
		wareSkuService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}


	/**
	 * 保存
	 */
	@PostMapping("/save")
	public R save_other(@RequestBody WareSku wareSku) {
		wareSkuService.save(wareSku);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	public R update(@RequestBody WareSku wareSku) {
		wareSkuService.updateById(wareSku);

		return R.ok();
	}

	/**
	 * 信息
	 */
	@GetMapping("/info/{id}")
	public R info(@PathVariable("id") Long id) {
		WareSku wareSku = wareSkuService.getById(id);

		return R.ok(wareSku);
	}

}
